package com.one.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.one.common.core.constants.Constants;
import com.one.common.core.domain.TableDataInfo;
import com.one.common.core.enums.ExamListType;
import com.one.common.core.enums.ResultCode;
import com.one.common.core.util.ThreadLocalUtil;
import com.one.common.redis.service.RedisService;
import com.one.common.security.exception.ServiceException;
import com.one.common.security.service.TokenService;
import com.one.friend.domain.exam.Exam;
import com.one.friend.domain.exam.dto.ExamDTO;
import com.one.friend.domain.exam.dto.ExamQueryDTO;
import com.one.friend.domain.exam.vo.ExamVO;
import com.one.friend.domain.user.UserExam;
import com.one.friend.manager.ExamCacheManager;
import com.one.friend.mapper.exam.ExamMapper;
import com.one.friend.mapper.user.UserExamMapper;
import com.one.friend.service.user.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamService implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Value("${jwt.secret}")
    private String secret;
    @Override
    public int enter(String token, ExamDTO examDTO) {
        //1. 判断当前竞赛是否存在
        Exam exam = examMapper.selectById(examDTO.getExamId());
        if(exam == null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        //2. 判断当前竞赛是否开赛
        if(exam.getStartTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
        //3. 判断当前用户是否已经报名
//        //拿取到用户id
//        Long userId = Long.valueOf(tokenService.getUserId(token, secret));
        //优化一下获取用户id的方法
        //通过ThreadLocal获取，每次进入拦截器时会判断延长token也会进行解析，此时将userId存入ThreadLocal当中
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examDTO.getExamId())
                .eq(UserExam::getUserId, userId));
        if(userExam != null){
            throw new ServiceException(ResultCode.EXAM_HAS_ENTER);
        }
        //存入redis
        examCacheManager.addUserExamCache(userId, examDTO.getExamId());
        //存入数据库
        userExam = new UserExam();
        userExam.setUserId(userId);
        userExam.setExamId(examDTO.getExamId());
        return userExamMapper.insert(userExam);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        //先查询缓存（u:e:l:用户id）  如果缓存能够查询到
        //如果查询不到   数据库当中再去查询  并且将数据库中的数据同步给redis
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            //从数据库中查询我的竞赛列表
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(), userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList, total);
    }
}
